package com.bdqn.gulimall.member.interceptor;

import com.bdqn.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.bdqn.common.constant.AuthServerConstant.LOGIN_USER;

/**
 * @Description: 登录拦截器
 **/

@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // /member/memberreceiveaddress/info/{id}

        String uri = request.getRequestURI();
        // AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = new AntPathMatcher().match("/member/**", uri);
        // boolean match1 = antPathMatcher.match("/payed/notify", uri);
        if (match) {
            return true;
        }

        //获取登录的用户信息
        MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(LOGIN_USER);

        if (attribute != null) {
            //把登录后用户的信息放在ThreadLocal里面进行保存
            loginUser.set(attribute);
            return true;
        } else {
            //未登录，返回登录页面
            request.getSession().setAttribute("msg", "请先进行登录");
            // response.setContentType("text/html;charset=UTF-8");
            // PrintWriter out = response.getWriter();
            // out.println("<script>alert('请先进行登录，再进行后续操作！');location.href='http://auth.yunmall.com/login.html'</script>");
            // session.setAttribute("msg", "请先进行登录");
            response.sendRedirect("http://auth.yunmall.com/login.html");
            return false;
        }

    }

    // @Override
    // public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    //
    // }
    //
    // @Override
    // public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {


}
